package com.zc.im.rabbitmq.consumer;

import com.zc.im.rabbitmq.AmqpConfig;
import com.zc.im.util.properties.RabbitmqProperties;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2017/7/21.
 */
public class ConsumerAccept {

    @Autowired
    private RabbitmqProperties rabbitmqProperties;

    @Autowired
    private AmqpConfig amqpConfig;

    @Bean
    SimpleMessageListenerContainer acceptContainer() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setQueues(amqpConfig.sendQueue());
        container.setExposeListenerChannel(true);
        container.setMaxConcurrentConsumers(1);
        container.setConcurrentConsumers(1);
        container.setConnectionFactory(amqpConfig.connectionFactory());
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式手工确认
        container.setQueueNames(rabbitmqProperties.getRabbitAcceptQueueName());
        container.setMessageListener(new ChannelAwareMessageListener() {
            public void onMessage(Message message, com.rabbitmq.client.Channel channel) throws Exception {
                byte[] body = message.getBody();
                System.out.println("收到消息 : " + new String(body));
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); //确认消息成功消费
            }
        });
        return container;
    }

}
